{% extends "base.html" %}
{% block title %}重复分析 - {{ super() }}{% endblock %}

{% block extra_css %}
<link href="/static/css/pages/ai-analysis/analysis-results.css" rel="stylesheet">
<link href="/static/css/analysis-result-details.css" rel="stylesheet">
<style>
    /* 重复分析页面样式 */
    .duplicate-analysis-container {
        max-width: 1280px;
        margin: 0 auto;
        padding: 0 1rem;
    }

    .stat-card-custom {
        background: white;
        border-radius: 0.75rem;
        padding: 1.5rem;
        border: 1px solid #e2e8f0;
        transition: all 0.3s ease;
        height: 100%;
    }

    .stat-card-custom:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    }

    .stat-card-custom .stat-value {
        font-size: 2rem;
        font-weight: 700;
        color: #1e293b;
        margin: 0.5rem 0;
    }

    .stat-card-custom .stat-label {
        color: #64748b;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .stat-card-custom .stat-trend {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        margin-top: 0.5rem;
        font-size: 0.75rem;
    }

    .trend-up {
        color: #10b981;
    }

    .trend-down {
        color: #ef4444;
    }

    .duplicate-tabs {
        background: white;
        border-radius: 0.75rem;
        padding: 0.25rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        margin-bottom: 1.5rem;
    }

    .duplicate-tab {
        flex: 1;
        padding: 0.75rem 1rem;
        text-align: center;
        border-radius: 0.5rem;
        font-weight: 500;
        color: #64748b;
        cursor: pointer;
        transition: all 0.2s ease;
        border: none;
        background: none;
    }

    .duplicate-tab.active {
        background: #4f46e5;
        color: white;
        box-shadow: 0 2px 4px rgba(79, 70, 229, 0.2);
    }

    .duplicate-tab:hover:not(.active) {
        background: #f1f5f9;
        color: #475569;
    }

    .duplicate-tab i {
        margin-right: 0.5rem;
    }

    .filter-section {
        background: white;
        border-radius: 0.75rem;
        padding: 1.5rem;
        border: 1px solid #e2e8f0;
        margin-bottom: 1.5rem;
    }

    .chart-container-custom {
        background: white;
        border-radius: 0.75rem;
        padding: 1.5rem;
        border: 1px solid #e2e8f0;
        margin-bottom: 1.5rem;
        min-height: 400px;
    }

    .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }

    .chart-title {
        font-size: 1.125rem;
        font-weight: 600;
        color: #1e293b;
    }

    .similarity-badge {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 500;
        margin-right: 0.5rem;
    }

    .similarity-high {
        background: #fee2e2;
        color: #dc2626;
    }

    .similarity-medium {
        background: #fef3c7;
        color: #d97706;
    }

    .similarity-low {
        background: #dbeafe;
        color: #2563eb;
    }

    .duplicate-table-container {
        background: white;
        border-radius: 0.75rem;
        padding: 1.5rem;
        border: 1px solid #e2e8f0;
        overflow: hidden;
    }

    .duplicate-table {
        width: 100%;
        border-collapse: collapse;
    }

    .duplicate-table th,
    .duplicate-table td {
        padding: 0.75rem 1rem;
        text-align: left;
        border-bottom: 1px solid #e2e8f0;
    }

    .duplicate-table th {
        background: #f8fafc;
        font-weight: 600;
        color: #475569;
    }

    .duplicate-table tbody tr:hover {
        background: #f8fafc;
    }

    .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        backdrop-filter: blur(4px);
        z-index: 10;
    }

    .pagination-custom {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0.5rem;
        margin-top: 1.5rem;
    }

    .page-btn {
        padding: 0.5rem 0.75rem;
        border: 1px solid #e2e8f0;
        background: white;
        border-radius: 0.375rem;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .page-btn:hover:not(.disabled) {
        background: #f1f5f9;
    }

    .page-btn.active {
        background: #4f46e5;
        color: white;
        border-color: #4f46e5;
    }

    .page-btn.disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    @media (max-width: 768px) {
        .duplicate-analysis-container {
            padding: 0 0.5rem;
        }

        .filter-section {
            padding: 1rem;
        }

        .chart-container-custom {
            padding: 1rem;
            min-height: 300px;
        }

        .duplicate-tabs {
            flex-wrap: wrap;
        }

        .duplicate-tab {
            flex: 1 1 calc(50% - 0.5rem);
            margin: 0.25rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="space-y-6 duplicate-analysis-container">
    <!-- 页面头部 -->
    <div class="flex justify-between items-center">
        <div>
            <h2 class="text-xl font-semibold text-slate-800">重复分析</h2>
            <p class="text-slate-600 mt-1">识别和分析重复信访问题，发现重点关注领域</p>
        </div>
        <div class="flex space-x-3">
            <button id="exportDuplicateBtn"
                    class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                <i class="fas fa-download mr-2"></i>导出报告
            </button>
            <button id="refreshDuplicateBtn"
                    class="px-4 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-colors">
                <i class="fas fa-sync-alt mr-2"></i>刷新
            </button>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6" id="duplicateStatsGrid">
        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-label">重复问题总数</div>
                    <div class="stat-value" id="totalDuplicates">0</div>
                    <div class="stat-trend trend-up">
                        <i class="fas fa-arrow-up"></i>
                        <span>12.5%</span>
                    </div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-blue-400 to-blue-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-copy text-white text-xl"></i>
                </div>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-label">高度重复问题</div>
                    <div class="stat-value" id="highDuplicates">0</div>
                    <div class="stat-trend trend-up">
                        <i class="fas fa-arrow-up"></i>
                        <span>8.3%</span>
                    </div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-red-400 to-red-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-exclamation-triangle text-white text-xl"></i>
                </div>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-label">涉及区域数</div>
                    <div class="stat-value" id="affectedRegions">0</div>
                    <div class="stat-trend trend-down">
                        <i class="fas fa-arrow-down"></i>
                        <span>3.2%</span>
                    </div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-green-400 to-green-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-map-marker-alt text-white text-xl"></i>
                </div>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="flex justify-between items-start">
                <div>
                    <div class="stat-label">平均相似度</div>
                    <div class="stat-value" id="avgSimilarity">0%</div>
                    <div class="stat-trend trend-up">
                        <i class="fas fa-arrow-up"></i>
                        <span>5.7%</span>
                    </div>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-purple-400 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-percentage text-white text-xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- 分析标签页 -->
    <div class="duplicate-tabs">
        <div class="flex space-x-1">
            <button class="duplicate-tab active" data-tab="similarity">
                <i class="fas fa-chart-bar"></i>相似度分析
            </button>
            <button class="duplicate-tab" data-tab="clusters">
                <i class="fas fa-project-diagram"></i>聚类分析
            </button>
            <button class="duplicate-tab" data-tab="popular">
                <i class="fas fa-fire"></i>热点问题
            </button>
            <button class="duplicate-tab" data-tab="trends">
                <i class="fas fa-chart-line"></i>趋势分析
            </button>
        </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">相似度范围</label>
                <select id="similarityFilter" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    <option value="">全部相似度</option>
                    <option value="high">高度相似 (80%+)</option>
                    <option value="medium">中度相似 (50-80%)</option>
                    <option value="low">低度相似 (<50%)</option>
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">区域筛选</label>
                <select id="regionFilter" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    <option value="">全部区域</option>
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">时间范围</label>
                <input type="date" id="startDate" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">至</label>
                <input type="date" id="endDate" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>
        </div>

        <div class="flex justify-end mt-4 space-x-3">
            <button id="resetFilters" class="px-4 py-2 border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors">
                重置
            </button>
            <button id="applyFilters" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                应用筛选
            </button>
        </div>
    </div>

    <!-- 图表区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="chart-container-custom">
            <div class="chart-header">
                <h3 class="chart-title">相似度分布</h3>
                <button class="text-slate-400 hover:text-slate-600">
                    <i class="fas fa-expand"></i>
                </button>
            </div>
            <div id="similarityChart" style="height: 350px;"></div>
        </div>

        <div class="chart-container-custom">
            <div class="chart-header">
                <h3 class="chart-title">重复问题聚类</h3>
                <button class="text-slate-400 hover:text-slate-600">
                    <i class="fas fa-expand"></i>
                </button>
            </div>
            <div id="clusterChart" style="height: 350px;"></div>
        </div>
    </div>

    <!-- 重复问题列表 -->
    <div class="duplicate-table-container">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-slate-800">重复问题详情</h3>
            <div class="flex space-x-2">
                <input type="text" placeholder="搜索问题..." class="px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                <button class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                    <i class="fas fa-search"></i>
                </button>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="duplicate-table">
                <thead>
                    <tr>
                        <th>问题描述</th>
                        <th>相似度</th>
                        <th>涉及区域</th>
                        <th>重复次数</th>
                        <th>首次发现</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="duplicateTableBody">
                    <!-- 动态生成的数据行 -->
                </tbody>
            </table>
        </div>

        <div class="pagination-custom" id="duplicatePagination">
            <!-- 分页按钮将动态生成 -->
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- 基础组件库 -->
<script src="/static/js/components/base/BaseComponent.js"></script>
<script src="/static/js/components/base/StatCard.js"></script>
<script src="/static/js/components/base/FilterPanel.js"></script>
<script src="/static/js/components/base/ChartContainer.js"></script>

<!-- 工具类库 -->
<script src="/static/js/utils/ApiClient.js"></script>
<script src="/static/js/utils/CacheManager.js"></script>
<script src="/static/js/utils/ErrorHandler.js"></script>
<script src="/static/js/utils/index.js"></script>

<!-- 图表库 -->
<script src="/static/vendor/echarts/echarts.min.js"></script>

<!-- 重复分析组件 -->
<script src="/static/js/components/analysis/DuplicateAnalysis.js"></script>

<!-- 统一分析结果管理脚本 -->
<script src="/static/js/pages/ai-analysis/analysis-results.js?v={{ timestamp }}"></script>

<!-- 重复分析页面专用脚本 -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化工具类
        const apiClient = new ApiClient({
            baseURL: '',
            timeout: 30000,
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const cacheManager = new CacheManager({
            prefix: 'duplicate_analysis_',
            ttl: 5 * 60 * 1000 // 5分钟缓存
        });

        const errorHandler = new ErrorHandler({
            container: 'duplicateAnalysisContainer',
            enableNotifications: true,
            enableLogging: true
        });

        // 设置全局API客户端
        window.apiClient = apiClient;
        window.cacheManager = cacheManager;
        window.errorHandler = errorHandler;

        // 初始化重复分析组件
        const duplicateAnalysis = new DuplicateAnalysis({
            id: 'duplicateAnalysis',
            container: document.querySelector('.duplicate-analysis-container'),
            apiClient: apiClient,
            autoRender: true
        });

        // 页面事件处理
        const pageEvents = {
            // 标签页切换
            initTabSwitching() {
                const tabs = document.querySelectorAll('.duplicate-tab');
                tabs.forEach(tab => {
                    tab.addEventListener('click', () => {
                        // 移除所有活动状态
                        tabs.forEach(t => t.classList.remove('active'));
                        // 添加当前活动状态
                        tab.classList.add('active');

                        // 触发组件标签页切换
                        const tabName = tab.dataset.tab;
                        duplicateAnalysis.switchTab(tabName);

                        // 重新调整图表大小
                        setTimeout(() => {
                            duplicateAnalysis.resizeCharts();
                        }, 100);
                    });
                });
            },

            // 筛选器处理
            initFilters() {
                const applyBtn = document.getElementById('applyFilters');
                const resetBtn = document.getElementById('resetFilters');

                applyBtn.addEventListener('click', () => {
                    const filters = {
                        similarity: document.getElementById('similarityFilter').value,
                        region: document.getElementById('regionFilter').value,
                        startDate: document.getElementById('startDate').value,
                        endDate: document.getElementById('endDate').value
                    };
                    duplicateAnalysis.applyFilters(filters);
                });

                resetBtn.addEventListener('click', () => {
                    document.getElementById('similarityFilter').value = '';
                    document.getElementById('regionFilter').value = '';
                    document.getElementById('startDate').value = '';
                    document.getElementById('endDate').value = '';
                    duplicateAnalysis.resetFilters();
                });
            },

            // 导出功能
            initExport() {
                const exportBtn = document.getElementById('exportDuplicateBtn');
                exportBtn.addEventListener('click', () => {
                    duplicateAnalysis.exportReport();
                });
            },

            // 刷新功能
            initRefresh() {
                const refreshBtn = document.getElementById('refreshDuplicateBtn');
                refreshBtn.addEventListener('click', () => {
                    refreshBtn.disabled = true;
                    refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>刷新中...';

                    duplicateAnalysis.refreshData().then(() => {
                        refreshBtn.disabled = false;
                        refreshBtn.innerHTML = '<i class="fas fa-sync-alt mr-2"></i>刷新';
                    }).catch(error => {
                        console.error('刷新失败:', error);
                        refreshBtn.disabled = false;
                        refreshBtn.innerHTML = '<i class="fas fa-sync-alt mr-2"></i>刷新';
                    });
                });
            },

            // 统计数据更新
            updateStats(data) {
                document.getElementById('totalDuplicates').textContent = data.total || 0;
                document.getElementById('highDuplicates').textContent = data.highSimilarity || 0;
                document.getElementById('affectedRegions').textContent = data.regions || 0;
                document.getElementById('avgSimilarity').textContent = (data.avgSimilarity || 0) + '%';
            },

            // 初始化所有事件
            init() {
                this.initTabSwitching();
                this.initFilters();
                this.initExport();
                this.initRefresh();

                // 监听组件数据更新事件
                duplicateAnalysis.on('data:loaded', (data) => {
                    this.updateStats(data.stats || {});
                });

                // 监听组件通知事件
                duplicateAnalysis.on('notification:show', (data) => {
                    console.log(`[${data.type.toUpperCase()}] ${data.message}`);
                    if (window.showNotification) {
                        window.showNotification(data.message, data.type);
                    }
                });
            }
        };

        // 初始化页面事件
        pageEvents.init();

        // 全局错误处理
        window.addEventListener('error', function(event) {
            errorHandler.handleError(event.error);
        });

        // 全局未处理的Promise拒绝
        window.addEventListener('unhandledrejection', function(event) {
            errorHandler.handleError(event.reason);
        });

        // 响应式处理
        window.addEventListener('resize', function() {
            clearTimeout(window.resizeTimeout);
            window.resizeTimeout = setTimeout(() => {
                duplicateAnalysis.resizeCharts();
            }, 250);
        });

        // 页面卸载时清理资源
        window.addEventListener('beforeunload', function() {
            duplicateAnalysis.destroy();
        });

        console.log('重复分析页面初始化完成');
    });
</script>
{% endblock %}